#!/usr/bin/env python3
# _*_ coding: utf-8 _*_
'''
把声卡读取的txt数据转换为wav数据
Requirements:
+ pyaudio - `pip install pyaudio`
+ py-webrtcvad - `pip install webrtcvad`
'''
import sys,os
import collections
from array import array
from struct import pack
import wave
import time
import signal
import pyaudio
import webrtcvad
import pandas as pd

FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = 16000


def record_to_file(path, data, sample_width):
    "Records from the microphone and outputs the resulting data to 'path'"
    # sample_width, data = record()
    data = pack('<' + ('h' * len(data)), *data)
    wf = wave.open(path, 'wb')
    wf.setnchannels(1)
    wf.setsampwidth(sample_width)
    wf.setframerate(RATE)
    wf.writeframes(data)
    wf.close()


if __name__ == '__main__':
    path = sys.argv[1]
    for category in os.listdir(path):
        #print(category)
        people_path = os.path.join(path,category)
        #print(people_path)
        for audio_txt in os.listdir(people_path):
            audio_name = os.path.splitext(audio_txt)[0]
            print(audio_txt)
            da =pd.read_csv(os.path.join(people_path , audio_txt),header=None).iloc[:,1:]
            print(da)
            da = da.values.T[0]
            print(os.path.join(people_path , audio_name + ".wav"))
            record_to_file(os.path.join(people_path , audio_name + ".wav"),da,2)


